<?php include ('layout/header.php'); ?>
<?php
$dalCountry = new DALCountry();

$countries = array();

$countryList = $dalCountry->getCountriesClosing();
for ($index = 0; $index < count($countryList); $index++) {
    $country = $countryList[$index];
    $c = new Country($country->id, $country->name, $country->url, $country->status);
    $countries[$index] = $c;
}


?>
<div id="page">
    <div class="config-setting">
        <h4>Config</h4>
        <div class="settings">
            <div class="col-md-2 bet-times">
                <label for="bettimes">Bet Times: </label>
                <select id="bettimes">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                </select>
            </div>
            
            <div class="col-md-3 bet-times">
                <label for="baseAmount">Base Amount: </label>
                <input type="number" name="baseAmount" id="baseAmount" min="10" max="100" placeholder="50" required/>
            </div>
            
            <div class="col-md-2 bet-times">
                <label for="wonPercent">Won percent: </label>
                <input type="number" name="wonPercent" id="wonPercent" min="5" max="20" placeholder="10" />
            </div>
            
        </div>
        <div class="table-responsive" id="configTbl">
            <table class="table table-striped table-bordered table-condensed">
                <thead>
                    <tr>
                        <th rowspan="2">Di chuyển</th>
                        <th rowspan="2">Phút</th>
                        <th colspan="2">Tỷ lệ</th>
                        <th colspan="2">Số trái</th>
                        <th rowspan="2">Xóa</th>
                    </tr>
                    <tr>
                        <th>From</th>
                        <th>To</th>
                        <th>From</th>
                        <th>To</th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="settingRow processing">
                        <td colspan="7">
                            <div class="progress progress-striped active">
                                <div class="progress-bar"  role="progressbar" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100" style="width: 85%">
                                    <span class="sr-only">85% Complete</span>
                                </div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
            <div class="setting_action">
                <input type="button" class="btn btn-info" value="Add" onclick="buildAppSettingRow()"/>
            </div>
        </div>
    </div>   
    <div class="bet-setting">
        <div class="wrapper">
            <div class="row show-grid">
                <div class="col-md-4"><h2>Country</h2></div>
                <div class="col-md-6"><h2>League</h2></div>
                <div class="col-md-2"><h2>Action</h2></div>
            </div>
            <div class="row">

                <div class="col-md-4">
                    <div class="triangle"></div>
                    <div id="countryList" class="panel">
                        <div class="display_country_status">
                            <ul>
                                <li><button type="button" class="btn btn-info" onclick="javascript:selectCountry('-1')">All</button></li>
                                <li><button type="button" class="btn btn-success" onclick="javascript:selectCountry('1')">Đang chọn</button></li>
                                <li><button type="button" class="btn btn-warning" onclick="javascript:selectCountry('0')">Không</button></li>
                            </ul>
                        </div>
                        <?php foreach ($countries as $country) : ?>
                            <div class="row" id="c_<?= $country->id ?>" data-country="<?= $country->id ?>">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" onclick="javascript:checkedCountry('<?= $country->id ?>')" <?= ($country->status == '1') ? 'checked="checked"' : '' ?>>
                                    </label>
                                </div>
                                <span class="countryLink" onclick="javascript:selectCountry('<?= $country->id ?>')"><?= $country->name ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="searchPanel">
                        <div class="searchText">
                            <input type="text" class="form-control" placeholder="Search" id="searchInput">
                        </div>
                    </div>
                    <div id="leaguesList" class="panel">
                        <div class="data"></div>
                        <div class="progress progress-striped active">
                            <div class="progress-bar"  role="progressbar" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100" style="width: 85%">
                                <span class="sr-only">85% Complete</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-2">
                    <div id="action" class="panel">
                        <button id="btnSave" type="button" class="btn btn-primary" onclick="javascript:save()">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>       
        


<script>
    function checkedCountry(id) {
        var countryRow = $('#c_' + id);
        var countryInput = $('input[type="checkbox"]', countryRow);

        $('#leaguesList .row').each(function() {
            leagueCountryId = $(this).attr('data-country');
            if (leagueCountryId === (id + '')) {
                $('input[type="checkbox"]', this).prop('checked', $(countryInput).prop('checked'));
            }
        });
    }

    function checkedLeague(leagueId, countryId) {
        var leagueRow = $('#l_' + leagueId);
        var leagueChecked = $('input[type="checkbox"]', leagueRow).prop('checked');

        var countryRow = $('#c_' + countryId);
        var countryInput = $('input[type="checkbox"]', countryRow);
        if (leagueChecked) {
            $(countryInput).prop('checked', 'checked');
        } else {
            //TODO find all league with same countryId - loop - and check value
            var allLeagueIsUnChecked = true;
            $('#leaguesList .row').each(function() {
                rowCountryId = $(this).attr('data-country');
                if (rowCountryId === countryId + '') {
                    var otherLeagueChecked = $('input[type="checkbox"]', this).prop('checked');
                    if (otherLeagueChecked) {
                        allLeagueIsUnChecked = false;
                        return false;
                    }
                }
            });
            if (allLeagueIsUnChecked) {
                $(countryInput).prop('checked', false);
            }
        }
    }

    $(function() {
        getAppSetting();
        getLeagueSetting();

        //register event
        $('#searchInput').keyup(function() {
            var txt = $(this).val();
            txt = txt.toLowerCase();
            $('#leaguesList .row.display').each(function(index, element) {
                var name = $('.leagueName', $(this)).text();
                name = name.toLowerCase();
                if (name.indexOf(txt) === -1) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
        });
        
        $('.table').delegate('.deleteSetting', 'click', function(){
            $(this).parents('.setting').remove();
        });
        
        $( ".table" ).sortable({
            items: "tr.setting",
            helper:"clone",
            zIndex: 99999,
            placeholder: "ui-state-highlight"
        });
    });
    
    function getAppSetting(){
        $.ajax({
            type: 'GET',
            url: 'export.php',
            data: {type: 'bet_rules'},
            cache: false,
            beforeSend: function() {
                $('.settingRow.processing').show();
            },
            complete: function() {
                $('.settingRow.processing').hide();
            },
            success: function(data) {
                insertAppSetting(data);
            }
        });
    }
    
    function getSettingRow(){
        var row = '<tr class="setting">';
            row += '<td><span class="arrow">&nbsp;Move</span></td>';        
            row += '<td><input type="text" class="minute" value="xMx"></td>';
            row += '<td><input type="text" class="rateFrom" value="xRFx"></td>';
            row += '<td><input type="text" class="rateTo" value="xRTx"></td>';
            row += '<td><input type="text" class="goalFrom" value="xGFx"></td>';
            row += '<td><input type="text" class="goalTo" value="xGTx"></td>';
            row += '<td><span class="glyphicon glyphicon-trash deleteSetting"></span></td>';
            row += '</tr>';
        return row;
    }
    
    function insertAppSetting(data){
        var out = JSON.parse(data);
        if(out.length === 2){
            bet_time = out[0];
            bet_str = bet_time.value;
            bet_item = bet_str.split(';');
            
            $('#bettimes').val(bet_item[0]);
            $('#baseAmount').val(bet_item[1]);
            $('#wonPercent').val(bet_item[2]);
            
            bet_setting = out[1].value.split("x0x");
            for(i = 0; i < bet_setting.length; i++){
                var setting = bet_setting[i];
                if(setting.length > 1){
                    buildAppSettingRow(setting);
                }
            }
        }
    }
    
    function buildAppSettingRow(data){
        var row = getSettingRow();
        var col;
        if(data && data.length > 0){
            col = data.split(";");
        }else{
            col = '00;1.01;1.05;0;7'.split(";");
        }
        row = row.replace('xMx', col[0]);
        row = row.replace('xRFx', col[1]);
        row = row.replace('xRTx', col[2]);
        row = row.replace('xGFx', col[3]);
        row = row.replace('xGTx', col[4]);
        
        $('.settingRow').before(row);
    }
    
    function getLeagueSetting(){
        $.ajax({
            type: 'GET',
            url: 'export.php',
            data: {type: 'league', id: '-1'},
            cache: false,
            success: function(data) {
                insertLeague(data);
            }
        });
    }

    function insertLeague(data) {
        var result = '';
        $('#leaguesList .progress').hide();
        var out = JSON.parse(data);
        for (i = 0; i < out.length; i++) {
            row = out[i];
            result += '<div class="row display" id="l_' + row.id + '" data-league="' + row.id + '" data-country="' + row.countryId + '"><div class="checkbox"><label>';
            result += '<input onclick="javascript:checkedLeague(' + row.id + ', ' + row.countryId + ')" type="checkbox" ' + ((row.status === '1') ? 'checked="checked"' : '') + '>';
            result += '</label></div>';
            result += '<span class="leagueName">' + row.name + '</span>';
            result += '</div>';
        }
        $('#leaguesList .data').html(result);
        countryHeight = $('#countryList').height();
        $('#leaguesList').height(countryHeight);
        $('#action').height(countryHeight);

    }

    function selectCountry(id) {
        $('#leaguesList .row').each(function() {
            $(this).removeClass('display');
            leagueCountryId = $(this).attr('data-country');
            var checked = $('input[type="checkbox"]', this).prop('checked');
            var display = false;
            if (id === '-1' || leagueCountryId === id) {
                display = true;
            } else if (id === '0') {
                display = !checked;
            } else if (id === '1') {
                display = checked;
            } else {
                display = false;
            }
            if (display) {
                $(this).addClass('display');
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    }

    function save() {
        var mess = [];
        var countries = [];
        var leagues = [];
        var setting = [];
        var failed = false;
        
        
        $('.setting').each(function(){
            var minute = $(this).find('.minute').val();
            var rateFrom = $(this).find('.rateFrom').val();
            var rateTo = $(this).find('.rateTo').val();
            var goalFrom = $(this).find('.goalFrom').val();
            var goalTo = $(this).find('.goalTo').val();
            
            if(isNaN(minute) || isNaN(rateFrom) || isNaN(rateTo) || isNaN(goalFrom) || isNaN(goalTo) ){
                failed = true;
            }else{
                setting += "x0x" + minute + ";" + rateFrom + ";" + rateTo + ";" + goalFrom + ";" + goalTo + ";";
            }
        });
        if(failed){
            alert('setting wrong');
            return false;
        }
        if(setting.length > 3){
            var SP = 'v0v';
            setting = setting.substr(3);
            var bTime = $('#bettimes').val();
            var bAmount = $('#baseAmount').val();
            var bWonPercent = $('#wonPercent').val();
            
            
            setting = bTime + ";" + bAmount + ";" + bWonPercent + SP + setting;
        }
        
        $('#countryList .row').each(function() {
            var id = $(this).attr('data-country');
            var checked = $('input[type="checkbox"]', this).prop('checked');
            item = new Object();
            item.id = id;
            item.status = (checked === true) ? 1 : 0;
            countries.push(item);
        });
        $('#leaguesList .row').each(function() {
            var id = $(this).attr('data-league');
            var checked = $('input[type="checkbox"]', this).prop('checked');
            item = new Object();
            item.id = id;
            item.status = (checked === true) ? 1 : 0;
            leagues.push(item);
        });
        mess['countries'] = countries;
        mess['leagues'] = leagues;
        mess['setting'] = setting;

        console.log(mess);

        $.ajax({
            type: 'POST',
            url: 'import.php',
            cache: false,
            data: {
                validate: 'JYlOjo821t6fvSOvOM7H764mEV4BSNZt3XiqH2skDU'
                , type: 'leagueStatus'
                , countries: mess.countries
                , leagues: mess.leagues
                , setting: mess.setting
            }, success: function(data) {
                if (data === '1') {
                    alert('done');
                } else {
                    alert(data);
                }
            }
        });
    }
</script>
<?php include ('layout/footer.php'); ?>